﻿
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using Newtonsoft.Json;
using Redis;

namespace VoteEventService
{
    internal class Helper
    {
        public static int TotalItemsEachBatch()
        {
            int total = 0;
            try
            {
                total = Convert.ToInt32(ConfigurationManager.AppSettings["TotalItemsEachBatch"]);
            }
            catch { }
            if (total > 0) return total;
            else return 10;
        }

        public static double TimerInterval()
        {
            double interval = 0;
            try
            {
                interval = Convert.ToDouble(ConfigurationManager.AppSettings["Interval"]);
            }
            catch { }
            if (interval > 0) return interval;
            else return 60000;
        }

        public static List<VoteLogObject> GetFromMessageQueues(int Total)
        {
            var redisCache = new VoteCache();
            int i = 0;
            var lst = new List<VoteLogObject>();
             //Get pageview of each article from article cache queue
            while (++i < Total)
            {
                string jsonItem = redisCache.DequeueItem();
                if (jsonItem == null)
                {
                    break;
                }
                var o = JsonConvert.DeserializeObject<VoteLogObject>(jsonItem);
                if (o != null) lst.Add(o);
            }
            return lst;
        }

        public static void UpdateToSQL(List<VoteLogObject> datas)
        {
            foreach (VoteLogObject t in datas)
            {
                DAL.Vote_Update(t.VoteLog_ToID, t.VoteLog_Round);
                DAL.VoteLog_Insert(t);
            }
        }

        public static void TextLog(string LOG_PATH, string message)
        {
            string path = LOG_PATH + DateTime.Now.Year + DateTime.Now.Month + "/";
            DirectoryInfo dir = new DirectoryInfo(path);
            if (!dir.Exists)
                dir.Create();

            string fileName = DateTime.Now.Day + ".txt";
            using (StreamWriter sw = File.AppendText(path + fileName))
            {
                sw.WriteLine(DateTime.Now + " - " + message);
            }
        }
    }
}
